package com.example.administrator.mobliesafe;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Environment;
import android.os.Message;
import android.os.SystemClock;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import android.os.Handler;
import android.widget.Toast;

import com.example.administrator.mobilesafe.utils.StreamTools;


import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;


public class SplashActivity extends Activity {
    SharedPreferences sharedPreferences;
    TextView tv_splash;
    String version;
    String discription;
    String apkuri;
    TextView textView;
    public static final int SHOW_UPDATE_DIALOG = 0;
    public static final int ENTER_HOME = 1;
    public static final int URL_ERROR = 2 ;
    public static final int NETWORK_ERROR = 3;
    public static final int JSON_ERROR = 4;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        copyDB();
        sharedPreferences = getSharedPreferences("config",MODE_PRIVATE);
        tv_splash = (TextView) findViewById(R.id.tv_version);
        version = getVersionInfo();
        tv_splash.setText("版本：" + version);

        boolean update = sharedPreferences.getBoolean("update",false);
        if(update){
            checkUpdate();
        }else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    enterHome();
                }
            }, 2000);
        }
        AlphaAnimation aa = new AlphaAnimation(0.2f,1f);
        aa.setDuration(500);
        findViewById(R.id.Splash).setAnimation(aa);
        textView = (TextView)findViewById(R.id.tv_update_info);
    }

    private void copyDB() {
        try {
            File file = new File(getFilesDir(),"address.db");
            if(file.exists()&&file.length()>0){
            }else{
                //数据库文件只需要拷贝一下，如果拷贝了，不需要重新拷贝了。
                AssetManager am = getAssets();
                InputStream is = am.open("address.db");
                //创建一个文件/data/data/包名/files/address.db
                FileOutputStream fos = new FileOutputStream(file);
                byte [] buffer = new byte[1024];
                int len = 0;
                while((len=is.read(buffer)) != -1){
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        public  void  handleMessage(Message message){
            super.handleMessage(message);
            switch (message.what){
                case SHOW_UPDATE_DIALOG:
                    showUpdateDialog();
                    break;
                case ENTER_HOME:
                    Toast.makeText(SplashActivity.this,"进入主页面",Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case URL_ERROR :
                    Toast.makeText(SplashActivity.this,"URL错误",Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case NETWORK_ERROR:
                    Toast.makeText(SplashActivity.this,"网络连接错误",Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case JSON_ERROR :
                    Toast.makeText(SplashActivity.this,"JSON解析错误",Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                default:break;
            }
        }
    };

    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("发现新版本");
        builder.setMessage(discription);
      //  builder.setCancelable(false);
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                enterHome();
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    FinalHttp finalHttp = new FinalHttp();
                    finalHttp.download(apkuri, Environment.getExternalStorageDirectory().getAbsolutePath() + "apk2.0", new AjaxCallBack<File>() {
                        @Override
                        public void onLoading(long count, long current) {
                            super.onLoading(count, current);
                            textView.setVisibility(View.VISIBLE);
                            int progress = (int) (current * 100 / count);
                            textView.setText("升级进度" + progress + "%");
                        }

                        @Override
                        public void onSuccess(File file) {
                            super.onSuccess(file);
                            installAPK(file);
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            t.printStackTrace();
                            Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();
                            super.onFailure(t, errorNo, strMsg);
                        }
                    });
                } else {
                    Toast.makeText(getApplicationContext(), "没有sd卡，请安装后再试", Toast.LENGTH_SHORT).show();
                    enterHome();
                    dialog.dismiss();
                    return;
                }
            }

            private void installAPK(File file) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-crchive");
                startActivity(intent);
            }
        });
        builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                enterHome();

            }
        });
        builder.show();
    }

    public void enterHome() {
        Intent intent = new Intent(this,HomeActivity.class);
        startActivity(intent);
        finish();
    }
    public void checkUpdate(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                long startTime = System.currentTimeMillis();
                Message message = Message.obtain();
                try {
                    URL url = new URL("http://192.168.1.102:8080/update.html");
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                    httpURLConnection.setRequestMethod("GET");

                    httpURLConnection.setConnectTimeout(4000);
                    int code = httpURLConnection.getResponseCode();
                    if(code == 200){
                        InputStream inputStream = httpURLConnection.getInputStream();
                        String result = StreamTools.readFromStream(inputStream);
                        JSONObject jsonObject = new JSONObject(result);
                        version = (String)jsonObject.get("version");
                        discription = (String)jsonObject.get("discription");
                        apkuri = (String) jsonObject.get("apkuri");
                        if(getVersionInfo().equals(version)){
                            message.what = ENTER_HOME;
                        }else {
                            message.what = SHOW_UPDATE_DIALOG ;
                        }
                    }
                } catch (MalformedURLException e) {
                    message.what = URL_ERROR;
                    e.printStackTrace();
                } catch (IOException e) {
                    message.what = NETWORK_ERROR ;
                    e.printStackTrace();
                } catch (JSONException e) {
                    message.what = JSON_ERROR ;
                    e.printStackTrace();
                }finally {
                    long endTime = System.currentTimeMillis();
                    long time = endTime-startTime;
                    if(time<2000){
                        SystemClock.sleep(2000-time);
                    }
                    handler.sendMessage(message);
                }
            }
        }).start();

    }
    private String getVersionInfo(){
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(),0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


}
